package com.example.feild.encryption.extension.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.Assert;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: 阿力
 * @date: 2020/4/23 15:50
 * @describe:
 */
public class ShortUrlTools {
    private static String queryFromApi(String url) throws IOException {
        // 网址如：http://www.aliyun.com/a=&b=，有特殊符号&请将 & 转化成%26，即：http://www.aliyun.com/a=%26b=
        Assert.hasLength(url, "请输入转换的地址");
        url = url.replaceAll("&", "%26");

        String AppCode = "d2d13dc7c3aa44929e6cf964473412ec";
        String urlSend = "https://superurl.market.alicloudapi.com/shorturlss?url=" + url;
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(urlSend).openConnection();
        httpURLConnection.setRequestProperty("Authorization", "APPCODE " + AppCode);
        int httpCode = httpURLConnection.getResponseCode();
        Assert.isTrue(200 == httpCode, String.format("短地址api接口请求失败,返回httpCode=%s(200 正常;400 权限错误;403 次数用完)", httpCode));
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        String json = sb.toString();
        JSONObject resp = JSONObject.parseObject(json);
        Assert.isTrue("100".equals(resp.getString("status")), resp.getString("msg"));
        return resp.getString("url");
    }

    public static void main(String[] args) throws IOException {
        System.out.println(queryFromApi("http://test-jhcp.caidashi.site/website/mapService?name=123&age=18"));
    }
}
